#include <iostream>
#include <unistd.h>
#include "../logs/log.h"

// 扩展以时间为日志滚动类型的模块
// 时间段滚动，取时间%gap，查看是第几个时间段，如果是60，就是第n个60s

enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink :public LogSink
{
    public:
    RollByTimeSink(const std::string& basename, TimeGap gap_type)
                :_basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
         case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;                   
        default:
            _gap_size = 60;
            break;
        }

        _cur_gap = Date::now() / _gap_size;
        //}
        // 获取创建的文件名
        std::string pathname = createNewFile();
        // 构造时创建日志文件目录，打开
        File::create_directory(File::path(pathname));
        // 追加写二进制
        _ofs.open(pathname, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void log(const char *data, size_t len)
    {
        time_t cur = Date::now();

        // 判断当前文件时间段
        if ((cur / _gap_size) != _cur_gap)
        {
            std::string pathname = createNewFile();
            // 一定要关闭旧的文件
            _ofs.close();
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
            _cur_gap = cur / _gap_size;
        }

        _ofs.write(data, len);
        assert(_ofs.good());
    }

private:
    std::string createNewFile()  // 超过大小创建新文件，获取文件名
    {
        time_t time = Date::now();
        struct tm lt;
        localtime_r(&time, &lt);
        // 追加文件名
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;  // 从1900年开始的
        filename << lt.tm_mon + 1;  // 0月开始算的
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";

        return filename.str();
    }

private:
    std::string _basename;  // 基准文件名，根据时间追加文件名 ./log/base-2022034233
    std::ofstream _ofs;
    size_t _cur_gap;  // 第几个时间段
    size_t _gap_size;  // 时间段大小
};


int main()
{
    // 功能测试
    std::unique_ptr<LoggerBuilder> builder(new GlobalLoggerBuilder());
    builder->buildLoggerName("sync-logger");
    builder->buildLoggerLevel(LogLevel::value::DEBUG);
    builder->buildFormatter("[%c]%m%n");
    builder->buildSink<StdoutSink>();
    builder->buildSink<RollByTimeSink>("./logfile/roll-sync-by-size-", TimeGap::GAP_SECOND);
    Logger::ptr logger = builder->build();

    time_t old = Date::now();
    while (Date::now() < old + 5)
    {
        logger->debug("测试日志");
        usleep(1000);
    }
    return 0
    ;
}